package com.zhao.dota.common.processor;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhao.dota.config.SteamConfig;
import com.zhao.dota.exception.SteamHttpException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

@Slf4j
public abstract class SteamProcessor {

    @Resource
    protected OkHttpClient okHttpClient;
    @Resource
    protected ObjectMapper objectMapper;
    @Resource
    private SteamConfig steamConfig;

    protected Request buildGet(String url, Map<String, ?> params) {
        Set<String> paramsSet = new TreeSet<>();
        if (params != null && !params.isEmpty()) {
            String strValue;
            for (Map.Entry<String, ?> e : params.entrySet()) {
                String key = e.getKey();
                Object value = e.getValue();
                if (value == null || !StringUtils.hasText((strValue = value.toString()))) {
                    continue;
                }
                paramsSet.add(key + "=" + strValue);
            }
        }
        paramsSet.add("key=" + steamConfig.getApiKey());
        return new Request.Builder().url(url + "?" + String.join("&", paramsSet)).get().build();
    }

    protected Request buildGet(String url, Param... params) {
        Set<String> paramsSet = new TreeSet<>();
        if (params != null) {
            for (Param param : params) {
                paramsSet.add(param.toString());
            }
        }
        paramsSet.add("key=" + steamConfig.getApiKey());
        return new Request.Builder().url(url + "?" + String.join("&", paramsSet)).get().build();
    }


    protected String sendRequest(Request request) {
        try {
            Response response = okHttpClient.newCall(request).execute();
            String result = response.body().string();
            if (log.isDebugEnabled()) {
                log.debug("请求[{}]返回值：\n {}", request.url(), result);
            }
            return result;
        } catch (IOException e) {
            throw new SteamHttpException(String.format("请求stem webApi失败，url:%s, body: %s", request.url(), request.body()), e);
        }
    }

    public <T> T readValue(String content, TypeReference<T> valueTypeRef) {
        try {
            return objectMapper.readValue(content, valueTypeRef);
        } catch (IOException e) {
            throw new SteamHttpException("返回json异常, json:" + content, e);
        }
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    protected static class Param {

        private String key;

        private Object value;

        @Override
        public String toString() {
            return this.key + "=" + this.value;
        }
    }

}
